layui.use(['form','layer','laydate','table','laytpl','element'],function(){
    var element = layui.element;
    var laydate = layui.laydate;
    var form = layui.form,
        layer=layui.layer;
    $ = layui.jquery,
        laytpl = layui.laytpl,
        table = layui.table;
    var currentIndex = parent.layer.getFrameIndex(window.name);//获取当前窗体索引
    //添加话术包
    form.on('submit(add)', function(formData){
        var submitData = [];
        var sortNums = ",";
        var flag = true;
        $(".layui-form-item").each(function () {
            var id  = $(this).attr("id");
            var flowName = "";
            var sortNum = 0;
            if($(this).find($(".layui-form-label")).length>0){
                console.log($(this).find($(".layui-form-label")).text());
                flowName = $(this).find($(".layui-form-label")).text();
            }
            if($(this).find($(".layui-input-block")).length>0){
                console.log($(this).find($(".layui-input-block")).find($("input[name='sortNum']")).val());
                sortNum = $(this).find($(".layui-input-block")).find($("input[name='sortNum']")).val();
                if(sortNums.indexOf(","+sortNum+",")!=-1){
                    console.log("");
                    flag = false;
                    return;
                }
                sortNums += sortNum+",";
            }
            if(flowName!=""&&sortNum!=""){
                submitData.push(flowSortObj.buildParam(id,flowName,sortNum));
            }
        });
        if(flag == false){
            layer.msg("操作失败，流程节点的顺序不能有重复");
            return;
        }

        if(submitData.length<=0){
            layer.msg("操作失败，没有流程信息");
            return;
        }
        //弹出loading
        var load = layer.msg('数据提交中，请稍候',{icon: 16,time:false,shade:0.8});
        var bo = verification(formData.form,null);
        if(bo){
            // var submitData = formData.field;
            saveData(submitData,load);
        }else{
            layer.close(load);
        }
    });

    function saveData(submitData,load){
        $.ajax({
            type: "POST",
            url:  baseUrl+'/flowConfig/saveFlowSorts?packageId='+packageId+'&flowSortStr='+encodeURIComponent(JSON.stringify(submitData)),
            dataType: 'json',
            success: function (data) {
                console.log(data);
                layer.close(load);
                if(data.code<=0){
                    layer.msg(data.msg);
                }else{
                    layer.msg("保存成功");
                    //重load flow数据
                    parent.referFlows();
                    //关闭本窗体
                    setTimeout(function () {
                        $("#cancel").click();
                    },1000);
                }
            },
            error: function () {
                layer.close(load);
                layer.msg("保存失败");
                return ;
            }
        });
    }

    $('#cancel').on('click',function () {
        parent.layer.close(currentIndex);//执行关闭
    });

    //验证表单
    function verification(form,iframeWin) {
        var config = {
            verify: {
                required: [
                    /[\S]+/
                    , '必填项不能为空'
                ]
                , phone: [
                    /^1\d{10}$|^$/
                    , '请输入正确的手机号'
                ]
                , email: [
                    /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$|^$/
                    , '邮箱格式不正确'
                ]
                , url: [
                    /(^#)|(^http(s*):\/\/[^\s]+\.[^\s]+)/
                    , '链接格式不正确'
                ]
                , number: [
                    /^\d+$|^$/
                    , '只能填写数字'
                ]
                , date: [
                    /^(\d{4})[-\/](\d{1}|0\d{1}|1[0-2])([-\/](\d{1}|0\d{1}|[1-2][0-9]|3[0-1]))*$|^$/
                    , '日期格式不正确'
                ]
                , identity: [
                    /(^\d{15}$)|(^\d{17}(x|X|\d)$|^$)/
                    , '请输入正确的身份证号'
                ]
            }
        };
        formElem = $(form);
        var button = $(this), verify = config.verify, stop = null
            , DANGER = 'layui-form-danger',PROMPT='required_prompt', field = {}
            , verifyElem = formElem.find('*[lay-verify-zdy]') //获取需要校验的元素
            , checkedElem = formElem.find('*[data-required]') //获取复选框
            ,rangeElem = formElem.find('*[data-range]')//获取范围判断的区间值

        //开始校验
        layui.each(verifyElem, function (_, item) {
            var othis = $(this), tips = '';
            var arr = othis.attr('lay-verify-zdy').split(',');
            for (var i in arr) {
                var ver = arr[i];
                var value = othis.val(), isFn = typeof verify[ver] === 'function';
                if(ver == 'number'&&value==''){
                    value = 0;
                }
                othis.removeClass(DANGER);
                if (verify[ver] && (isFn ? tips = verify[ver](value, item) : !verify[ver][0].test(value))) {
                    layer.msg(tips || verify[ver][1], {
                        icon: 5
                        , shift: 6
                    });
                    //非移动设备自动定位焦点
                    if (!layui.device().android && !layui.device().ios) {
                        if(item.type=='text'){
                            item.focus();
                        }else if(item.type=="select-one"){
                            $(item).next("div").find("input").focus();
                            $(item).next("div").find("input").attr("readonly");
                        }
                    }
                    othis.addClass(DANGER);
                    return stop = true;
                }
            }
        });
        if (stop) return false;
        //返回序列化表单元素， JSON 数据结构数据。
        return true;
    }
});

var flowSortObj = {
    buildParam:function (flowId,flowName,sort) {
        var flowSortObj = {};
        flowSortObj.flowId = flowId;
        flowSortObj.flowName = flowName;
        flowSortObj.sort = sort;
        return flowSortObj;
    }
};